<template>
  <div class="role-table-con">
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="getData('reset')" >
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="角色编码">
                    <el-input v-model="listSearch.condition.code" clearable placeholder="请输入角色编码"
                      @keyup.enter.native="getData('search')" @clear="getData('search')" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="角色名称">
                    <el-input v-model="listSearch.condition.name" clearable placeholder="请输入角色名称"
                      @keyup.enter.native="getData('search')" @clear="getData('search')" />
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="getData('search')">查询</el-button>
                <el-button @click="getData('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>
            <el-button :icon="Plus" type="primary" @click="addEditBtn('add')"
              v-permission="'ROLE:CREATE-EDIT'"></el-button>
            <el-dropdown :hide-on-click="false" style="margin: 0 10px;" trigger="click">
              <el-button title="过滤表头">
                <el-icon :size="18">
                  <Grid />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-checkbox-group v-model="selectTitle" size="small" @change="checkboxChange">
                    <el-dropdown-item v-for="item in showTitle" :key="item.prop">
                      <el-checkbox :label="item.label" :value="item.prop" />
                    </el-dropdown-item>
                  </el-checkbox-group>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total" @get-page="handPage"
          :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight" :loading="pageParams.loadIng">
          <template #roleStatus="scope">
            {{ isEnabled[scope.row.isEnabled] }}
          </template>
          <template #handle="scope">

            <el-button type="primary" size="small" link @click="addEditBtn('edit', scope.row)"
              v-permission="'ROLE:PAGE'">编辑</el-button>
            <el-button type="primary" size="small" link @click="permissionBtn(scope.row)">权限分配</el-button>
            <el-button type="primary" size="small" link @click="isDisableBtn(scope.row)">{{ scope.row.isEnabled == 1
              ? "禁用" : "启用" }}</el-button>
            <el-button type="danger" size="small" link v-permission="'ROLE:DELETE'"
              @click="delBtn(scope.row)">删除</el-button>
              <el-button type="primary" size="small" link @click="detailBtn(scope.row)"
              v-permission="'ROLE:DETAIL'">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <addAndEdit ref="roleAddEditRef" @refresh="getData('reset')" @searchEdit="getData('search')"></addAndEdit>
    <permissionDis ref="permissionDisRef" @refresh="getData('search')" :saveMenuList="saveMenuList">
    </permissionDis>
    <FormDetail :detailData="detailData" ref="detailRef"></FormDetail>
  </div>
</template>

<script setup lang='ts'>
import { reactive, onMounted, ref, defineAsyncComponent, nextTick, onUnmounted } from "vue";
import _ from "lodash"
import { storeToRefs } from "pinia";
import { Search, Plus, Refresh } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  rolePageApiPost,
  roleDeleteApiDelete,
  roleRelationAuthorityListApiPost,
  roleDetailApiGet,
  roleDisableOrEnableApiPut,
} from "@/api/userMangement";
import useInstance from "@/hooks/useInstance";
import { menuStore } from "@/store/menu";
import { roleListStore } from "./pageStore"
import mittBus from '@/utils/mitt';
const { saveMenuList } = menuStore();
const { detailData, tableProp } = storeToRefs(roleListStore())
const { global } = useInstance();

const addAndEdit = defineAsyncComponent(
  () => import("./components/addAndEdit.vue")
);
const permissionDis = defineAsyncComponent(
  () => import("./components/permission.vue")
);
const roleAddEditRef = ref<{ show: (type: string, row?: any) => void }>();
const permissionDisRef = ref<{
  show: (type: string, row?: any, roleList?: any) => void;
}>();
const detailRef = ref<{ show: (title: string, row?: any) => void }>()
const isEnabled: any = {
  "1": "启用",
  "2": "禁用"
}
const onlyTableRef=ref()
const listSearch = reactive({
  pageNum: 1,
  pageSize: 20,
  condition: {
    code: null,
    name: null,
    id: null,
  },
  orders: ["created_time desc"],
});
const pageParams = reactive({
  total: 0,
  loadIng: false,
  tableData: [],
  tableHeight: 500,
});
const selectTitle = ref<any>([])

const detailBtn = async (row: any) => {
  try {
    const res = await roleDetailApiGet({ id: row.id })
    if (res.code != 20000) return
    detailData.value = detailData.value.map(item => {
      if (item.prop == "isEnabled") {
        return {
          ...item,
          value: isEnabled[res.data[item.prop]]

        }
      } else {
        return {
          ...item,
          value: res.data[item.prop]
        }
      }
    })
    detailRef.value.dialogBasic.height = 300
    detailRef.value?.show('edit')
  } catch (error) {

  }
}
const showTitle = computed(() => {
  return tableProp.value.propsList.filter(it => it.label != "操作")
})
const checkboxChange = (val: string[]) => {
  pageParams.loadIng = true
  // 进入的 全部为 true 没有的为false
  tableProp.value.propsList = tableProp.value.propsList.map((item: any) => {
    if (val.includes(item.prop)) {
      return {
        ...item,
        hidden: true
      }
    } else if (item.label == "操作") {
      return {
        ...item,
        hidden: true
      }
    } else {
      return {
        ...item,
        hidden: false
      }
    }
  })
  pageParams.loadIng = false
}
onMounted(() => {
  selectTitle.value = tableProp.value.propsList.filter(it => it.hidden && it.label != "操作").map(item => item.prop)
  getData("search");

});


const getData = async (type: string) => {
  pageParams.loadIng = true;
  if (type === "reset") {
    listSearch.pageNum = 1;
    listSearch.pageSize = 20;
    listSearch.condition.name = null;
    listSearch.condition.code = null;
    listSearch.condition.id = null;
    onlyTableRef.value.initPagination()
  }
  try {
    const res = await rolePageApiPost(listSearch);
    if (res.code == 20000) {
      pageParams.tableData = res.data.records
      pageParams.total = res.data.total;
      pageParams.loadIng = false;
    }
  } catch (error) {
    console.log("accountPageApiPost");
  }finally{
    mittBus.emit('scrollUpdate')
  }
};
const permissionBtn = async (row: any) => {
  try {
    //roleRelationAuthorityListApi
    const res = await roleRelationAuthorityListApiPost({ roleCode: row.code });
    if (res.code == 20000) {
      console.log(res.data);
      const arr = res.data.map((it) => it.authorityCode);
      permissionDisRef.value?.show("add", row, arr);
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "数据查询失败",
    });
  }
};
const addEditBtn = async (type: string, row?: any) => {
  if (type === "add") {
    roleAddEditRef.value?.show("add");
  } else {
    const res = await roleDetailApiGet({ id: row.id })
    roleAddEditRef.value?.show("edit", res.data);
  }
};
const handPage = (val: { pageNum: number; pageSize: number }) => {
  listSearch.pageNum = val.pageNum;
  listSearch.pageSize = val.pageSize;
  getData("search");
};
const delBtn = async (row: any) => {
  const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.name}`);
  if (flag) {
    const res = await roleDeleteApiDelete({ id: row.id });
    console.log(res.data);
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "数据删除成功",
      });
      getData("search");
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败",
      });
    }
  }
};
const isDisableBtn = async (row: any) => {
  const str = row.isEnabled == 1 ? "是否确定禁用该角色？" : "是否确定启用该角色？"
  const flag = await global.$myconfirm(`${str}`);
  if (flag) {
    const res = await roleDisableOrEnableApiPut({ id: row.id, isEnabled: row.isEnabled == 1 ? 2 : 1 });
    console.log(res.data);
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: row.isEnabled == 1 ? "角色禁用成功" : "角色启用成功",
      });
      getData("search");
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败",
      });
    }
  }

}
</script>

<style lang="scss" scoped>
.role-table-con {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;
    // height: 100%;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>